﻿using NPOI.SS.UserModel;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using Utilities;

using WssClient;

namespace EasyExcel
{
    /// <summary>
    /// Excel文档对象
    /// </summary>
    public class ExcelDoc
    {
        private string mbFileName { get; }
        private string saveExcelFile;
        public NpoiExcel Npoi { get; }
        public ExcelDoc(string fileName)
        {
            //获取项目启动目录
            //string currDir = Environment.CurrentDirectory;
            //this.mbFileName = $"{currDir}/{dic}/{fileName}";
            this.mbFileName = GetFileNamePath(fileName);
            this.Npoi = new NpoiExcel(mbFileName);
        }

        private string GetFileNamePath(string fileName)
        {
            return $"{Path.Combine(GVar.CfgPath, fileName)}";
        }
        //public ExcelDoc(string fileName, string dic = "cfg")
        //{
        //    this.mbFileName = $"{dic}/{fileName}";
        //    this.Npoi = new NpoiExcel(mbFileName);
        //}
        /// <summary>
        /// 针对wps第一次打开总是会有错误，增加一个预热功能
        /// </summary>
        public void Preheat()
        {
            ExportToExcel exp = new ExportToExcel(false);
        }
        /// <summary>
        /// 已经导出成功的Sheet名称
        /// </summary>
        public List<string> hadExp = new List<string>();
        /// <summary>
        /// 打印预览
        /// </summary>
        public bool PrintPreView(bool deleteTmpFile = true)
        {
            SaveTmp();
            //System.Threading.Thread.Sleep(500);
            if(string.IsNullOrEmpty(saveExcelFile)) return false;
            ExportToExcel exp = new ExportToExcel(saveExcelFile);
            exp.PrintPreView();
            exp.CloseAll();
            try
            {
                if(deleteTmpFile && File.Exists(saveExcelFile)) File.Delete(saveExcelFile);
            }
            catch { }

            return true;
        }
        public bool Print(bool deleteTmpFile = true)
        {
            try
            {
                SaveTmp();
                //System.Threading.Thread.Sleep(500);
                LogHelper.Debug("saveExcelFile : " + saveExcelFile);
                if(string.IsNullOrEmpty(saveExcelFile)) return false;
                ExportToExcel exp = new ExportToExcel(saveExcelFile);
                exp.Print();
                exp.CloseAll();
                if(deleteTmpFile && File.Exists(saveExcelFile)) File.Delete(saveExcelFile);
            }
            catch(Exception e)
            {
                LogHelper.Error("Print Exception: " + e.ToString());
            }
            return true;
        }
        /// <summary>
        /// 设置当前Sheet
        /// </summary>
        /// <param name="sn"></param>
        /// <returns></returns>
        public bool SetSheetByName(string sn)
        {
            Npoi.errorMsg = string.Empty;
            Npoi.setSheetByName(sn);
            return string.IsNullOrEmpty(Npoi.errorMsg);
        }
        /// <summary>
        /// 设置单元格的值
        /// </summary>
        /// <param name="r">行：序号0开始</param>
        /// <param name="c">列：序号0开始</param>
        /// <param name="obj"></param>
        public void SetCell(int r, int c, object obj)
        {
            Npoi.setCellValue(r, c, obj);
        }
        /// <summary>
        /// 公式重新刷新
        /// </summary>
        public void Recalculation()
        {
            Npoi.RecountFormula();
        }
        /// <summary>
        /// 保存临时文件
        /// </summary>
        /// <returns></returns>
        private bool SaveTmp()
        {
            DelSheetList();
            Recalculation();
            string tmpFileName = DateTime.Now.Ticks + "tmp.xlsx";
            tmpFileName = GetFileNamePath(tmpFileName);
            Npoi.SaveAs(tmpFileName);
            saveExcelFile = tmpFileName;
            return true;
        }

        /// <summary>
        /// 导出到Pdf文件
        /// </summary>
        /// <param name="deleteTmpFile"></param>
        /// <returns></returns>
        public bool ExpPdf(bool deleteTmpFile = true)
        {
            ExportToExcel exp = new ExportToExcel(mbFileName);
            exp.Convert2PDF(mbFileName);
            exp.CloseAll();

            return true;
        }
        /// <summary>
        /// 删除不在清单中的工作表
        /// </summary>
        /// <param name="sourceName"></param>
        private void DelSheetList()
        {
            Npoi.DelSheetList(hadExp);
        }
        /// <summary>
        /// 复制当前行，插入下一行
        /// </summary>
        /// <param name="rowIdx"></param>
        public void CopyRow(int rowIdx, int targetRowIdx)
        {
            Npoi.CopyRow(rowIdx, targetRowIdx);
        }

        public void InsertBlankRow(int rowIdx, int colSpan, ICellStyle cellStyle = null, bool isFontBold = false, string fontName = "", short fontSize = 0)
        {
            Npoi.InsertBlankRow(rowIdx, colSpan, cellStyle, isFontBold, fontName, fontSize);
        }
    }
}
